const app = getApp()

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封装的微信请求
 * @param {String} URL 请求地址
 * @param {Object} WXRequestData 请求数据
 * @param {Object} Params 配置信息
 */
const WXRequest = function (URL, WXRequestData = {}, Method, Loading = '') {
  const Header = { 'content-type': 'application/x-www-form-urlencoded' }
  const method = Method || 'GET'
  if (wx.getStorageSync('token')) {
    WXRequestData.token = wx.getStorageSync('token')
  } else {
    wx.showToast({
      title: '查无Token，请稍后再试！',
      icon: 'none',
      duration: 2000
    })
    return
  }
  if (!Loading) {
    wx.showLoading({
      title: '加载中...',
    })
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: app.globalData.requestUrl + URL,
      header: Header,
      data: WXRequestData,
      method: method,
      success: (res) => {
        if (!Loading) {
          wx.hideLoading()
        }
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res)
        }
      },
      fail: (error) => {
        wx.hideLoading()
        reject(error)
      }
    })
  })
}

module.exports = {
  formatTime: formatTime,
  WXRequest: WXRequest
}
